<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	/**
	 * Authenticates a user.
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		//echo 'username: ' . $this->username ." and pw: " . $this->password;exit;
		$user=User::model()->findByAttributes(array('username'=>$this->username));
		
		//print_r($user);exit;
		
        if($user===null)
            $this->errorCode="Error: Username Invalid!!! Please try again or contact your manager for further instructions.";
        else if($user->password!==$this->password)  //PENDING ENCRYPTION else if($user->password!==md5($this->password))
            $this->errorCode="Error: Password Invalid!!! Please try again or contact your manager for further instructions.";
        else
        {
			/**
			* If the user is valid check if it's enabled or not
			*/
			if($user->enabled) {
				$this->setState('iduser', $user->iduser);
				$this->setState('name', $user->fullname);
				$this->setState('team_id', $user->team_relation->idteam);	
				$this->setState('team_name', $user->team_relation->short_name);	
				$this->setState('restricted', $user->restricted);
				//pull this user's role to check for priviledges
				$userRole = Role::model()->findByPk($user->idrole);
				
				//fill priviledges for this user based on role checks
				$this->setState('role', $userRole->name);
				$this->setState('can_create_edit_roles', $userRole->can_create_edit_roles);
				$this->setState('can_create_edit_users', $userRole->can_create_edit_users);
				$this->setState('can_create_edit_shifts', $userRole->can_create_edit_shifts);
				$this->setState('can_create_edit_qshifts', $userRole->can_create_edit_qshifts);
				$this->setState('can_create_callbacks', $userRole->can_create_callbacks);
				$this->setState('can_edit_callbacks', $userRole->can_edit_callbacks);
				$this->setState('can_create_shift_change', $userRole->can_create_shift_change);
				$this->setState('can_edit_shift_change', $userRole->can_edit_shift_change);
				$this->setState('can_create_qshift_change', $userRole->can_create_qshift_change);
				$this->setState('can_edit_qshift_change', $userRole->can_edit_qshift_change);
				
				$this->errorCode=self::ERROR_NONE;
			} else {
				$this->errorCode="Error: User disabled!!! Please contact your manager for further instructions.";
			}
        }
        return !$this->errorCode;
    }
}